import Vue from 'vue'
import Vuex from 'vuex'
import $http from '../http';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: [],
    user: {},
    products: []
  },
  mutations: {
    setUsers(state, data) {
      state.users = data;
      console.log('state.users', state.users);
    },
    setUser(state, data) {
      state.user = data;
    },
    delUser(state, data) {
      var index = state.users.findIndex((item) => data.id === item.id);
      console.log('deluser index', index);
      state.users.splice(index, 1);
    },
    setProducts(state, data) {
      state.products = data
    }

  },
  actions: {
    GET_USERS(context) {
      return new Promise((resolve, reject) => {
        $http.get('/api/users').then((res) => {
          context.commit('setUsers', res.list);
          resolve(res);
        }, (err) => {
          reject(err)
        });
      })
    },

    UPDATE_USER(context, data) {
      return new Promise((resolve, reject) => {
        $http.put('/api/user', data).then((res) => {
          resolve(res)
        }, (err) => {
          reject(err)
        })
      })
    },
    GET_USER(context, data) {
      return new Promise((resolve, reject) => {
        $http.get('/api/user?id=' + data).then((res) => {
          context.commit('setUser', res);
          resolve(res)
        }, (err) => {
          reject(err)
        })
      })
    },
    ADD_USER(context, data) {
      return new Promise((resolve, reject) => {
        $http.post('/api/user', data).then((res) => {
          resolve(res);
        }, (err) => {
          reject(err)
        })
      })
    },
    GET_PROUDCTS(context) {
      return new Promise((resolve, reject) => {
        $http.get('/api/products').then((res) => {
          context.commit('setProducts', res.list);
          resolve(res);
        }, (err) => {
          reject(err)
        })
      })
    }
  },
  modules: {},
  getters: {

  }
})